<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-card type="inner" title="云服务清单">
          <a-row :gutter="24">
            <a-col :span="10">
                <a-form-item label="结算时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
<!--                  <j-date ref="payTime" v-decorator="[ 'thisPayTime']" @change="dateChange"></j-date>-->
                  <j-date ref="payTime" v-decorator="[ 'thisPayTime']"></j-date>
                </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="优惠项目" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="jinanGovernmentLedgerAttachedTable.loading"
            :columns="jinanGovernmentLedgerAttachedTable.columns"
            :dataSource="jinanGovernmentLedgerAttachedTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"/>
        </a-tab-pane>

      </a-tabs>

    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">结算</a-button>
    </template>
  </a-modal>
</template>

<script>

  import pick from 'lodash.pick'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import JDate from '@/components/jeecg/JDate'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
  import JUpload from '@/components/jeecg/JUpload'

  export default {
    name: 'cloudServiceMoneyModel2',
    mixins: [JEditableTableMixin],
    components: {
      JDate,
      // JEditableTable,
      JSelectDepart,
      JMultiSelectTag,
      JUpload
    },
    data() {
      return {
        data:[],
        payMoney:'',
        lastYearMoney:'',
        noSetTime:'',
        labelCol: {
          xs: { span: 22 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 10 },
          sm: { span: 18}
        },
        disableSubmit:false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          updateTime:{},
          office:{},
          principal:{},
          principalPhone:{rules: [{validator: this.validatePhone}]},
          principalMail:{rules: [{validator: this.validateEmail}]},
          linkman:{},
          linkmanPhone:{rules: [{validator: this.validatePhone}]},
          linkmanMail:{rules: [{validator: this.validateEmail}]},
          systemName:{},
          mainUses:{},
          tos:{},
        },
        refKeys: ['jinanGovernmentLedgerAttached', ],
        tableKeys:['jinanGovernmentLedgerAttached', ],
        activeKey: 'jinanGovernmentLedgerAttached',
        // 服务器申请附表
        jinanGovernmentLedgerAttachedTable: {
          loading: false,
          dataSource: [],
          columns: [
            {  //这一个隐藏字段不能去掉，解决360浏览器不兼容问题
              title: '优惠项目',
              key: '',
              type: FormTypes.hidden,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '优惠项目',
              key: 'thisProject',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '金额',
              key: 'thisProjectMoney',
              type: FormTypes.inputNumber,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },
            {
              title: '说明',
              key: 'remarks',
              type: FormTypes.input,
              defaultValue: '',
              placeholder: '请输入${title}',
              align:"center",
            },

          ]
        },
        url: {
          add: "/jinanDredge/dredgeMain/pay",
          edit: "/jinanDredge/dredgeMain/pay",
          getMoney:"/jinanDredge/dredgeMain/getMoney"
          // jinanGovernmentLedgerAttached: {
          //   list: '/jinanServer/jinanGovernmentLedgerMain/queryJinanGovernmentLedgerAttachedByMainId'
          // },
        }
      }
    },
    methods: {
      /** 调用完edit()方法之后会自动调用此方法 */
      edit(record) {
        debugger
        this.data=record;
       let sysOrgCode=record[0].sysOrgCode;
        if (typeof this.editBefore === 'function') this.editBefore(record)
        this.visible = true
        this.activeKey = this.refKeys[0]
        this.form.resetFields()
        this.model = Object.assign({}, record)
        if (typeof this.editAfter === 'function') this.editAfter(this.model);
      },
      editAfter() {
        let rowNum = this.addDefaultRowNum;
        this.eachAllTable((item) => {
          item.add(rowNum)
        })

        let fieldval = pick(this.model,'office', 'officeName','systemName', 'serverName', 'noSetTime', 'openTime', 'lastPayTime', 'yearMoney', 'lastYearMoney')
        this.$nextTick(() => {
            this.form.setFieldsValue(fieldval)
          })
      },
      /** 整理成formData */
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue);
        var table = this.$refs.jinanGovernmentLedgerAttached;
        var ids = table.selectedRowIds;//选中的数据
        var values = allValues.tablesValue[0].values;
        var arr = new Array();
        if(ids.length>0){//说明是自选
          values.forEach(value=>{
            ids.forEach(caseId=>{
              let id = caseId.split("-")[2];
              if(value.id==id){
                arr.push(value);
              }
            })
          })
        }else{//默认全部
          arr = values;
        }


        return {
          ...main, // 展开
          jinanGovernmentLedgerAttachedList:this.data,
          jinanGovernmentHistoryRemaksList: arr,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      validateEmail(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/).test(value)){
            callback()
          }else{
            callback("请输入正确格式的邮箱!")
          }
        }
      },
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}/).test(value)){
            callback()
          }else{
            callback("请输入正确格式的电话号码!");
          }
        }
      },
      /** 删除被选中的行 */
      removeSelectedRows() {
        debugger
        this.removeRows(this.selectedRowIds)
        this.selectedRowIds = []
      },
      /** 删除
       *
一行或多行 */
      handleConfirmDelete() {
        this.removeSelectedRows()
      },
      removeRows(id) {
        debugger
        let ids = id
        if (!(id instanceof Array)) {
          if (typeof id === 'string') {
            ids = [id]
          } else {
            throw  `JEditableTable.removeRows() 函数需要的参数可以是string或Array类型，但提供的却是${typeof id}`
          }
        }

        let rows = cloneObject(this.rows)
        ids.forEach(removeId => {
          // 找到每个id对应的真实index并删除
          const findAndDelete = (arr) => {
            for (let i = 0; i < arr.length; i++) {
              if (arr[i].id === removeId || arr[i].id === this.caseId + removeId) {
                arr.splice(i, 1)
                return true
              }
            }
          }
          // 找到rows对应的index，并删除
          if (findAndDelete(rows)) {
            // 找到values对应的index，并删除
            findAndDelete(this.inputValues)
            // 将caseId去除
            let id = this.removeCaseId(removeId)
            this.deleteIds.push(id)
          }
        })
        this.rows = rows
        this.$emit('deleted', this.getDeleteIds())
        this.$nextTick(() => {
          // 更新formValues
          this.updateFormValues()
        })
        return true
      },
      handleDelete(props) {
        debugger
        // 参数解释
        let { rowId, target } = props
        target.removeRows(rowId)
      },

    }
  }
</script>

<style scoped>
</style>